import Foundation
import SDWebImage
import SwiftMessages

class UserView: CornerView {

    @IBOutlet weak var avatarImageView: AvatarImageView!
    @IBOutlet weak var fullnameLabel: UILabel!
    @IBOutlet weak var idLabel: UILabel!
    @IBOutlet weak var descriptionScrollView: UIScrollView!
    @IBOutlet weak var descriptionLabel: CollapsingLabel!
    @IBOutlet weak var addContactLineView: UIView!
    @IBOutlet weak var addContactButton: StateResponsiveButton!
    @IBOutlet weak var openBotLineView: UIView!
    @IBOutlet weak var openBotButton: UIButton!
    @IBOutlet weak var unblockLineView: UIView!
    @IBOutlet weak var unblockButton: StateResponsiveButton!
    @IBOutlet weak var sendLineView: UIView!
    @IBOutlet weak var sendButton: UIButton!
    @IBOutlet weak var verifiedImageView: UIImageView!
    @IBOutlet weak var moreButton: StateResponsiveButton!
    @IBOutlet weak var developButton: CornerButton!
    @IBOutlet weak var appPlaceView: UIView!

    @IBOutlet weak var descriptionScrollViewHeightConstraint: NSLayoutConstraint!
    
    private weak var superView: BottomSheetView?
    private var user: UserItem!
    private var appCreator: UserItem?
    private var relationship = ""
    private var conversationId: String = ""

    private lazy var editAliasNameController: UIAlertController = {
        let vc = UIApplication.currentActivity()!.alertInput(title: Localized.PROFILE_EDIT_NAME, placeholder: Localized.PROFILE_FULL_NAME, handler: { [weak self](_) in
            self?.saveAliasNameAction()
        })
        vc.textFields?.first?.addTarget(self, action: #selector(alertInputChangedAction(_:)), for: .editingChanged)
        return vc
    }()

    override func awakeFromNib() {
        super.awakeFromNib()
        descriptionLabel.delegate = self
    }
    
    @objc func alertInputChangedAction(_ sender: Any) {
        guard let text = editAliasNameController.textFields?.first?.text else {
            return
        }
        editAliasNameController.actions[1].isEnabled = !text.isEmpty
    }

    func updateUser(user: UserItem, animated: Bool = false, refreshUser: Bool = true, superView: BottomSheetView?) {
        self.superView = superView
        self.user = user

        idLabel.text = Localized.PROFILE_MIXIN_ID(id: user.identityNumber)
        verifiedImageView.isHidden = !user.isVerified
        developButton.isHidden = true

        if user.isVerified {
            verifiedImageView.image = #imageLiteral(resourceName: "ic_user_verified")
            verifiedImageView.isHidden = false
        } else if user.isBot {
            verifiedImageView.image = #imageLiteral(resourceName: "ic_user_bot")
            verifiedImageView.isHidden = false
        } else {
            verifiedImageView.isHidden = true
        }

        layoutIfNeeded()
        if user.isBot, let appDescription = user.appDescription, !appDescription.isEmpty {
            descriptionLabel.text = appDescription
            descriptionScrollViewHeightConstraint.constant = descriptionLabel.intrinsicContentSize.height
            descriptionLabel.isHidden = false
            developButton.isHidden = false
            appPlaceView.isHidden = false
        } else {
            descriptionScrollViewHeightConstraint.constant = 0
            descriptionLabel.isHidden = true
            developButton.isHidden = true
            appPlaceView.isHidden = true
        }

        guard user.relationship != relationship else {
            return
        }

        relationship = user.relationship

    }

    @IBAction func appCreatorAction(_ sender: Any) {
        guard let creator = appCreator else {
            return
        }

        updateUser(user: creator, animated: true, superView: superView)
    }

    @IBAction func dismissAction(_ sender: Any) {
        superView?.dismissPopupControllerAnimated()
    }

    @IBAction func moreAction(_ sender: Any) {
        superView?.dismissPopupControllerAnimated()
        let alc = UIAlertController(title: user.fullName, message: user.identityNumber, preferredStyle: .actionSheet)
        alc.addAction(UIAlertAction(title: Localized.PROFILE_SHARE_CARD, style: .default, handler: { [weak self](action) in
            self?.shareAction()
        }))
        
        alc.addAction(UIAlertAction(title: Localized.DIALOG_BUTTON_CANCEL, style: .cancel, handler: nil))
        UIApplication.currentActivity()?.present(alc, animated: true, completion: nil)
    }

    @IBAction func previewAvatarAction(_ sender: Any) {
        guard !user.avatarUrl.isEmpty, avatarImageView.sd_imageProgress.isFinished, let superView = superView as? UserWindow else {
            return
        }
        let frame = avatarImageView.convert(avatarImageView.bounds, to: superView)
        let avatarPreviewImageView = AvatarPreviewImageView(frame: frame)
        avatarPreviewImageView.image = avatarImageView.image
        avatarPreviewImageView.layer.cornerRadius = avatarImageView.layer.cornerRadius
        avatarPreviewImageView.clipsToBounds = true
        avatarImageView.isHidden = true
        superView.addSubview(avatarPreviewImageView)
        if #available(iOS 11.0, *) {
            superView.contentBottomConstraint.constant = -self.frame.height - superView.safeAreaInsets.vertical
        } else {
            superView.contentBottomConstraint.constant = -self.frame.height
        }
        UIView.animate(withDuration: 0.25, animations: {
            superView.layoutIfNeeded()
            avatarPreviewImageView.layer.cornerRadius = 0
            avatarPreviewImageView.bounds.size = CGSize(width: superView.frame.width,
                                                        height: superView.frame.width)
            avatarPreviewImageView.center = CGPoint(x: superView.frame.width / 2,
                                                    y: superView.frame.height / 2)
        }, completion: { (finished: Bool) -> Void in
            superView.userViewPopupView = superView.popupView
            superView.popupView = avatarPreviewImageView
        })
    }
    
    private func addMuteAlertAction(alc: UIAlertController) {
        if user.isMuted {
            alc.addAction(UIAlertAction(title: Localized.PROFILE_UNMUTE, style: .default, handler: { [weak self](action) in
                self?.unmuteAction()
            }))
        } else {
            alc.addAction(UIAlertAction(title: Localized.PROFILE_MUTE, style: .default, handler: { [weak self](action) in
                self?.muteAction()
            }))
        }
    }

    private func saveAliasNameAction() {
        guard let aliasName = editAliasNameController.textFields?.first?.text, !aliasName.isEmpty else {
            return
        }
        showLoading()
    }

    private func shareAction() {

    }

    private func blockAction() {
        showLoading()

    }

    private func muteAction() {
        let alc = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alc.addAction(UIAlertAction(title: Localized.PROFILE_MUTE_DURATION_8H, style: .default, handler: { [weak self](alert) in
            self?.saveMuteUntil(muteIntervalInSeconds: muteDuration8H)
        }))
        alc.addAction(UIAlertAction(title: Localized.PROFILE_MUTE_DURATION_1WEEK, style: .default, handler: { [weak self](alert) in
            self?.saveMuteUntil(muteIntervalInSeconds: muteDuration1Week)
        }))
        alc.addAction(UIAlertAction(title: Localized.PROFILE_MUTE_DURATION_1YEAR, style: .default, handler: { [weak self](alert) in
            self?.saveMuteUntil(muteIntervalInSeconds: muteDuration1Year)
        }))
        alc.addAction(UIAlertAction(title: Localized.DIALOG_BUTTON_CANCEL, style: .cancel, handler: nil))
        UIApplication.currentActivity()?.present(alc, animated: true, completion: nil)
    }

    private func unmuteAction() {
        saveMuteUntil(muteIntervalInSeconds: 0)
    }

    private func saveMuteUntil(muteIntervalInSeconds: Int64) {
        showLoading()
        let userId = user.userId
        
    }

    private func editNameAction() {
        editAliasNameController.textFields?.first?.text = user.fullName
        UIApplication.currentActivity()?.present(editAliasNameController, animated: true, completion: nil)
    }

    private func removeAction() {
        showLoading()
    }

    @IBAction func unblockAction(_ sender: Any) {
        guard !unblockButton.isBusy else {
            return
        }
        unblockButton.isBusy = true
    }


    @IBAction func sendAction(_ sender: Any) {
        superView?.dismissPopupControllerAnimated()
        if let conversationVC = UIApplication.rootNavigationController()?.viewControllers.last as? ConversationViewController, conversationVC.dataSource?.category == ConversationDataSource.Category.contact && conversationVC.dataSource?.conversation.ownerId == user.userId {
            return
        }

//        UIApplication.rootNavigationController()?.pushViewController(withBackRoot: ConversationViewController.instance(conversation: conversationVC.dataSource?.conversation))
    }

    @IBAction func openAction(_ sender: Any) {
        let userId = user.userId
        let conversationId: String
        if let vc = UIApplication.rootNavigationController()?.viewControllers.last as? ConversationViewController {
            conversationId = vc.conversationId
        } else {
            conversationId = self.conversationId
        }
        
    }

    @IBAction func addAction(_ sender: Any) {
        guard !addContactButton.isBusy else {
            return
        }
        addContactButton.isBusy = true
    }

    private func showLoading() {
        NotificationCenter.default.postOnMain(name: .ConversationDidChange, object: ConversationChange(conversationId: conversationId, action: .startedUpdateConversation))
    }

    class func instance() -> UserView {
        return Bundle.main.loadNibNamed("UserView", owner: nil, options: nil)?.first as! UserView
    }
}

extension UserView: CollapsingLabelDelegate {
    
    func coreTextLabel(_ label: CoreTextLabel, didSelectURL url: URL) {
        dismissAction(self)
    }
    
    func collapsingLabel(_ label: CollapsingLabel, didChangeModeTo newMode: CollapsingLabel.Mode) {
        let textSize = descriptionLabel.intrinsicContentSize
        descriptionScrollViewHeightConstraint.constant = textSize.height
        descriptionScrollView.isScrollEnabled = newMode == .normal && textSize.height > descriptionScrollView.frame.height
        layoutIfNeeded()
    }
    
}

extension UserView {
    
    class AvatarPreviewImageView: UIImageView {
        
        override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
            return false
        }
        
    }
    
}
